//
// Created by hsj on 2024-1-8.
// ip获取域名【！！！国内失败几率很高！！！】
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#ifdef WIN32
//windows minGW64
//inet_ntop函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>
//#pragma comment(lib,"ws2_32.lib")
#else
//linux  gcc
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#define BUF_SIZE 30
void error_handling(char *message);

int main(int argc, char *argv[]){
    int i;
    struct hostent *host;
//    struct sockaddr_in addr;

//    memset(&addr, 0, sizeof(addr));
//    addr.sin_addr.s_addr=inet_addr("10.211.55.5");

    //向第一个参数传递的地址信息的字节数，IPv4时为4，IPv6时为16。
//    host=gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);

    const char *add = "211.144.27.126";
    char p[30];
    inet_pton(AF_INET, add, p);
    host = gethostbyaddr(p, strlen(p), AF_INET);
    if(!host)
        error_handling(" gethost... error");

    printf("0fficial name: %s \n", host->h_name);

    for(i=0; host->h_aliases[i]; i++)
        printf("Aliases %d: %s \n", i+1, host->h_aliases[i]);

    printf("Address type: %s \n",(host->h_addrtype==AF_INET)?"AF_INET":"AF_INET6");

    for(i=0; host->h_addr_list[i]; i++)
        printf("IP addr %d: %s \n", 1+1,inet_ntoa(*(struct in_addr* )host->h_addr_list[i]));

    return EXIT_SUCCESS;
}

void error_handling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}